<template>
  <div :class="{ show: isShow }" class="header-search">
    <svg-icon
      class-name="search-icon"
      icon="search"
      @click.stop="onShowClick"
    ></svg-icon>
    <el-select
      ref="headerSearchSelectRef"
      class="header-search-select"
      v-model="search"
      filterable
      remote
      default-frist-option
      placeholder="Search"
      :remote-method="querySearch"
      :loading="loading"
      @change="handleChange"
    >
      <el-option
        v-for="option in searchOption"
        :key="option.item.path"
        :label="option.item.title.join('>')"
        :value="option.item"
      ></el-option>
    </el-select>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { filterRoutes } from '@/utils/route.js'
import { useRouter } from 'vue-router'
import Fuse from 'fuse.js'
import { generateRoutes } from './fusedata'
const isShow = ref(false)
const search = ref('')
const onShowClick = () => {
  isShow.value = !isShow.value
}
const router = useRouter()
const searchPool = computed(() => {
  const filterRoute = filterRoutes(router.getRoutes())
  return generateRoutes(filterRoute)
})

const fuse = new Fuse(searchPool.value, {
  shouldSort: true,
  minMatchCharLength: 1,
  keys: [
    {
      name: 'title',
      weight: 0.7
    },
    {
      name: 'path',
      weight: 0.3
    }
  ]
})
const searchOption = ref([])
const querySearch = (query) => {
  if (query !== '') {
    searchOption.value = fuse.search(query)
  } else {
    searchOption.value = []
  }
}
const handleChange = (val) => {
  router.push(val.path)
}

const headerSearchSelectRef = ref(null)
const onClose = () => {
  headerSearchSelectRef.value.blur()
  isShow.value = false
  searchOption.value = []
}

watch(isShow, (newVal) => {
  if (newVal) {
    document.body.addEventListener('click', onClose)
  } else {
    document.body.removeEventListener('click', onClose)
  }
})
</script>

<style lang="scss" scoped>
.header-search {
  height: 28px;
  .search-icon {
    cursor: pointer;
    font-size: 24px;
    vertical-align: middle;
  }
  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    ::v-deep .el-input__inner {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
    }
  }
  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>
